// reflex.js
Page({
  data: {
    positions: [],
    reflexZones: [],
    allReflexZones: [],
    currentPosition: 'all'
  },

  onLoad() {
    this.loadPositions()
    this.loadReflexZones()
  },

  // 加载体位数据
  loadPositions() {
    const positions = [
      { value: 'all', name: '全部' },
      { value: 'hand', name: '手部' },
      { value: 'foot', name: '足部' },
      { value: 'ear', name: '耳部' }
    ]
    this.setData({ positions })
  },

  // 加载反射区数据（从API）
  loadReflexZones() {
    this.getReflex()
  },
  //获取单个反射区的详情
  getReflexOne(id){
    wx.request({
      url: 'http://localhost:8081/reflexZone/reflexOne?id='+id,
      method: 'GET'
    })
  },
  // 从数据库获取反射区数据并映射
  getReflex(){
    wx.request({
      url: 'http://localhost:8081/reflexZone/reflexAll',
      method: 'GET',
      success: (res) => {
        const list = Array.isArray(res.data) ? res.data : []
        const mapped = list.map(item => {
          const { value: positionEnum, text: positionText } = this.normalizePosition(item.position1)
          return {
            id: item.id,
            name: item.name,
            position: positionEnum,
            positionText,
            function: item.function1,
            location: item.location1,
            operation: item.operation,
            images: this.normalizeFirstImage(item.images),
            isFree: item.isFree === 1,
            price: item.price || 0
          }
        })

        // 缓存全量数据并根据当前筛选渲染
        const current = this.data.currentPosition
        const reflexZones = current === 'all' ? mapped : mapped.filter(x => x.position === current)
        this.setData({ allReflexZones: mapped, reflexZones })
      },
      fail: (err) => {
        console.error('获取反射区失败:', err)
        this.setData({ reflexZones: [], allReflexZones: [] })
        wx.showToast({ title: '获取反射区失败', icon: 'none' })
      }
    })
  },
  // 规范化位置字段：兼容英文枚举与中文值
  normalizePosition(value) {
    const v = (value || '').toString().trim().toLowerCase()
    if (v === 'hand' || value === '手部') return { value: 'hand', text: '手部' }
    if (v === 'foot' || value === '足部') return { value: 'foot', text: '足部' }
    if (v === 'ear' || value === '耳部') return { value: 'ear', text: '耳部' }
    return { value: 'other', text: '其他' }
  },
  // 若为逗号分隔的URL，取首图
  normalizeFirstImage(images) {
    if (!images) return ''
    const str = images.toString().trim()
    const first = str.split(',')[0].trim()
    return first
  },
  // 体位点击事件
  onPositionTap(e) {
    const position = e.currentTarget.dataset.value
    this.setData({ currentPosition: position })
    // 基于缓存做本地筛选，避免重复请求
    const all = this.data.allReflexZones || []
    const reflexZones = position === 'all' ? all : all.filter(x => x.position === position)
    this.setData({ reflexZones })
  },

  // 反射区点击事件
  onReflexTap(e) {
    const reflexId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/reflex-detail/reflex-detail?id=${reflexId}`
    })
  }
})
